﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Core.SimpleTemp.Common;
using Microsoft.EntityFrameworkCore;

namespace Core.Toolkit.DbInitializer
{
    public static class DbInitializerHelp
    {
        static string assemblyNames = "Core.SimpleTemp.Repositories;Core.SimpleTemp.Application";
        public static void Initialize(DbContext context, WebAppOptions _webAppOptions)
        {
            if (!String.IsNullOrEmpty(assemblyNames))
            {
                var listType = new List<Type>();
                var objList = new List<DbInitializer>();
                var arrAssemb = assemblyNames.Split(';');

                //循环程序集
                foreach (var assemblyName in arrAssemb)
                {
                    Assembly assembly = Assembly.Load(assemblyName);

                    //var list = assembly.GetTypes().Where(a => a.GetInterfaces().Contains(typeof(IDbInitializer)) && a.Name != nameof(DbInitializerHelp));
                    var list = assembly.GetTypes().Where(a => a.IsSubclassOf(typeof(DbInitializer)) && a.Name != nameof(DbInitializerHelp));
                    if (list != null && list.Any())
                        listType.AddRange(list);
                }

                //动态创建对象
                foreach (var item in listType)
                {
                    var p = (DbInitializer)Activator.CreateInstance(item);
                    objList.Add(p);
                }

                //执行对象 initialize方法
                objList = objList.OrderBy(a => a.Sort).ToList();
                foreach (var item in objList)
                {
                    item.Initialize(context, _webAppOptions);
                }

            }
        }
        public static DateTime GetRandomDate()
        {
            return new DateTime(DateTime.Now.Year, new Random().Next(1, 12), new Random().Next(1, 28));
        }
        public static bool GetRandomBool()
        {
            return new Random().Next(0, 1) == 0;
        }

        
    }
}
